const dgram = require('dgram')
const udpServer = dgram.createSocket('udp4')
let _port = 6000
let udpPort = 6500
let udpServerTimer = null
let broadcastInterval = 3000
let broadcastContent = ''

/**
 * 创建UDP服务器
 * @param {Number} options/port 端口号
 * @param {Function} options/onconnect 发生连接时的回调函数
 * @param {Function} options/onmessage 收到信息时的回调函数
 * @param {Function} options/onerror 发生错误时的回调函数
 * @param {Function} options/onclose 服务关闭时的回调函数
 * @param {String} options/broadcastContent 要广播的内容
 * @param {Number} options/broadcastInterval 广播的时间间隔
 */
const createUdpServer = (options = {}) => {
  // 开始监听
  udpServer.on('listening', () => {
    let address = udpServer.address()
    console.log('udpServer is listening')
    console.log('udpServer ip: ', address.address)
    console.log('udpServer port: ', address.port)
  })
  // 发生连接
  udpServer.on('connect', (...args) => {
    console.log('udpServer is connected')
    options.onconnect && options.onconnect(...args)
  })
  // 收到信息
  udpServer.on('message', (msg, rinfo) => {
    console.log('udpServer receive message', (msg || '').toString(), rinfo)
    options.onmessage && options.onmessage(msg, rinfo)
  })
  // 发生错误
  udpServer.on('error', (err) => {
    console.log('udpServer error', err)
    options.onerror && options.onerror(err)
  })
  // 服务关闭
  udpServer.on('close', (...args) => {
    console.log('udpServer close')
    clearInterval(udpServerTimer)
    options.onclose && options.onclose(...args)
  })
  // 启动服务
  udpServer.bind(_port, () => {
    clearInterval(udpServerTimer)
    udpServerTimer = setInterval(() => {
      // 广播模式
      udpServer.setBroadcast(true)
      udpServer.send(broadcastContent, udpPort, '255.255.255.255')
    }, broadcastInterval)
  })
}

const start = (options = {}) => {
  options = options || {}
  _port = options._port || _port
  udpPort = options.port || udpPort
  broadcastInterval = options.broadcastInterval || broadcastInterval
  broadcastContent = options.broadcastContent || ''
  createUdpServer(options)
}

const stop = () => {
  clearInterval(udpServerTimer)
  udpServer.close()
}

const send = (data = '') => {
  data = data || ''
  udpServer.send(data, udpPort, '255.255.255.255')
}

// 获取服务器对象
const getServer = () => {
  return udpServer
}

module.exports = {
  getServer,
  start,
  stop,
  send
}
